package cc.c3p0.admin.common.filter;

import cc.c3p0.admin.common.constants.SystemConstants;
import cc.c3p0.admin.utils.JwtHelper;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 权鉴过滤器
 * Created by binchao on 2017/5/10.
 */
public class AuthorizationFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(AuthorizationFilter.class);

    @Value("${auth.urls.excludePathPatterns}")
    private String excludePathPatterns;

    @Value("${system.jwt.secretkey}")
    private String secretKey;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOG.info("正在初始化权限过滤器。。。");
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getRequestURI();
        LOG.info("当前访问的路径:" + path);
        for (String s : excludePathPatterns.split(",")) {
            if (s.equals(path)) {
                LOG.info("当前路径无需拦截。。。");
                chain.doFilter(request, response);
                return;
            }
        }
        LOG.info("拦截路径：" + path);
        // 从header中得到token
        String token = req.getHeader(SystemConstants.AUTHORIZATION);
        if (StringUtils.isEmpty(token)) {
            LOG.info("用户未登录。");
            request.getRequestDispatcher("/unlogin").forward(request, response);
            return;
        }

        // 验证token
        Claims claims = null;
        String userId = null;
        if (token.startsWith("Bearer ")) {
            claims = JwtHelper.parseJWT(token.substring(7), secretKey);
        }

        if (null != claims) {
            userId = (String) claims.get(SystemConstants.CURRENT_USER_ID);
        }
        if (!StringUtils.isEmpty(userId)) {
            LOG.info("用户令牌验证通过！");
            LOG.info("开始验证权限。。。");
            // TODO
            LOG.info("权限验证通过。。。");
            //如果token验证成功，将token对应的用户id存在request中，便于之后注入
            request.setAttribute(SystemConstants.CURRENT_USER_ID, userId);
            chain.doFilter(request, response);
        } else {
            LOG.info("用户令牌无效！");
            request.getRequestDispatcher("/unvalidtoken").forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
